//
//  SFNetBean.swift
//  SeeFM_Swift
//
//  Created by CBCT_MBP on 2021/6/21.
//

import UIKit


class SFNetBean: NSObject {

    static let shared = SFNetBean()
    
    
    public func getIdfa() -> String {
        return ASIdentifierManager.shared().advertisingIdentifier.uuidString
    }
    
    public func systemVersion() -> String {
        return UIDevice.current.systemVersion
    }
    
    public func jsonFormat() -> String {
        return "application/SF+json; version=1;"
    }
    
    static var appVersion: String {
        return Bundle.main.infoDictionary?["CFBundleShortVersionString"] as! String
    }
    
    public func appBuild() -> String {
        let info = Bundle.main.infoDictionary?["CFBundleVersion"] as? String
        return info ?? ""
    }
    
    public func appLFVersion() -> String {
        return "SF/" + SFNetBean.appVersion + "/" + SFNetBean.shared.appBuild()
    }
    
    public func systemHardwareName() -> String {
        return UIDevice.current.deviceName()
    }
    
    public func userAgent() -> String {
        return String.init(format: "iOS|%@|%@|%@|%@", self.systemVersion(),self.appLFVersion(),self.systemHardwareName(),self.channelName())
    }
    
    func getIFAddresses() -> String {
        
        var addresses = [Any]()
        var ifaddr : UnsafeMutablePointer<ifaddrs>? = nil
        if getifaddrs(&ifaddr) == 0 {
            var ptr = ifaddr
            while (ptr != nil) {
                let flags = Int32(ptr!.pointee.ifa_flags)
                var addr = ptr!.pointee.ifa_addr.pointee
                if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) {
                    if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) {
                        var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                        if (getnameinfo(&addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count),nil, socklen_t(0), NI_NUMERICHOST) == 0) {
                            if let address = String(validatingUTF8:hostname) {
                                addresses.append(address)
                            }
                        }
                    }
                }
                ptr = ptr!.pointee.ifa_next
            }
            freeifaddrs(ifaddr)
        }
        return addresses.first as? String ?? "192.168.1.1"
    }
    
    public func channelName() -> String {
        var channel = ""
        #if DEBUG
        channel = "CBCT_TEST"
        #else
        channel = "App Store"
        #endif
        return channel
    }
    
    
    
}
